//
//  QMAMiniSDKDelegateImp.m
//  QQMiniAppSDK
//
//  Created by raymonddeng on 2021/1/29.
//
#import "QMAContextDelegateImp.h"
#import "MBProgressHUD.h"
#import "UIImageView+WebCache.h"
#import "SimpleWebViewController.h"
#import "TZImagePickerController.h"
#import <QQMiniGameLogin/QQMiniGameLogin.h>
#import <CoreServices/CoreServices.h>
#import <SSZipArchive/SSZipArchive.h>

#define DEMO_BITMAP_TEST(bitmap, flag) ((bitmap & (flag)) == (flag))

@interface MAPickerController : UIImagePickerController
@property (nonatomic, strong) void (^callBack)(id _Nullable media, NSError * _Nullable error);
@property (nonatomic, strong) QMAMediaChooseConfigModel *model;
@end

@implementation MAPickerController
@end

@interface QMAContextDelegateImp()
@property (nonatomic, strong) void(^imageSelectCallBack)(NSArray *imageArrays,NSError *error);

@end

@implementation QMAContextDelegateImp

- (void)log:(MALogLevel)level msg:(NSString *)msg {
    NSString *strLevel = nil;
    switch (level) {
        case MALogLevelError:
            strLevel = @"Error";
            break;
        case MALogLevelWarn:
            strLevel = @"Warn";
            break;
        case MALogLevelInfo:
            strLevel = @"Info";
            break;
        case MALogLevelDebug:
            strLevel = @"Debug";
            break;
        default:
            strLevel = @"Undef";
            break;
    }
    NSLog(@"%@|%@", strLevel, msg); //小游戏运行日志信息
}

- (BOOL)unzipFileFromPath:(NSString *)sourcePath toDstPath:(NSString *)dstPath withError:(NSError *_Nullable __autoreleasing *)error {
    //MARK: 可自行替换
    return [SSZipArchive unzipFileAtPath:sourcePath toDestination:dstPath];
}

#pragma mark - 图片选择器

- (void)selectMediaFromCameraWithModel:(QMAMediaChooseConfigModel *)model
                              parentVC:(UIViewController *)parentVC
                       completionBlock:(void (^)(id _Nullable, NSError *_Nullable))completionBlock {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] == NO) {
        if (completionBlock) {
            completionBlock(nil, [NSError errorWithDomain:@"QMASelectMedia" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"no permission"}]);
        }
        return;
    }
    
    MAPickerController *camera = [MAPickerController new];
    camera.model = model;
    camera.sourceType = UIImagePickerControllerSourceTypeCamera;
    // 现在只有单独选择媒体和图片
    if (DEMO_BITMAP_TEST(model.chooseTypeMask, QMAMediaChooseTypeMaskImage)) {
        camera.mediaTypes = @[ (NSString *)kUTTypeImage];
        camera.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
    } else if (DEMO_BITMAP_TEST(model.chooseTypeMask, QMAMediaChooseTypeMaskVideo)) {
        camera.mediaTypes = @[ (NSString *)kUTTypeMovie ];
        camera.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
        camera.videoMaximumDuration = model.videoConfig.maxVideoDuration;
        camera.cameraDevice = model.videoConfig.isFront ? UIImagePickerControllerCameraDeviceFront : UIImagePickerControllerCameraDeviceRear;
        BOOL origin = DEMO_BITMAP_TEST(model.compressTypeMask, QMAMediaCompressTypeMaskOriginal);
        camera.videoQuality = origin ? UIImagePickerControllerQualityTypeIFrame1280x720 : UIImagePickerControllerQualityTypeIFrame960x540;
    }
    camera.delegate = self;
    camera.callBack = completionBlock;
    [parentVC presentViewController:camera animated:YES completion:nil];
}

#pragma mark UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info {
    if (![picker isKindOfClass:[MAPickerController class]]) {
        [picker dismissViewControllerAnimated:YES completion:nil];
        return;
    }
    
    MAPickerController *cameraPicker = (MAPickerController *)picker;
    
    // 视频需要等待处理完毕才能收起选图器
    if (picker.cameraCaptureMode == UIImagePickerControllerCameraCaptureModeVideo) {
        NSURL *mediaUrl = info[UIImagePickerControllerMediaURL];
        if (mediaUrl) {
            QMACameraVideoModel *videoModel = [QMACameraVideoModel new];
            videoModel.asset = [AVURLAsset URLAssetWithURL:mediaUrl options:nil];
            if (cameraPicker.callBack) {
                cameraPicker.callBack(videoModel, nil);
            }
            UIView *keywindow = [UIApplication sharedApplication].keyWindow;
            //TODO: 宿主可自行替换loading
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:keywindow animated:YES];
            QMAMediaChooseConfigModel *model = cameraPicker.model;
            __weak __typeof(cameraPicker) weakCameraPicker = cameraPicker;
            model.videoConfig.processCompletionBlock = ^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    __strong __typeof(weakCameraPicker) strongCamera = weakCameraPicker;
                    [hud hideAnimated:YES];
                    [strongCamera dismissViewControllerAnimated:YES completion:nil];
                });
            };
        }
        return;
    }
    
    if (picker.cameraCaptureMode == UIImagePickerControllerCameraCaptureModePhoto) {
        QMACameraImageModel *imageModel = [QMACameraImageModel new];
        imageModel.image = info[UIImagePickerControllerOriginalImage];
        if (cameraPicker.callBack) {
            cameraPicker.callBack(imageModel, nil);
        }
    }
    
    [cameraPicker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    if (![picker isKindOfClass:[MAPickerController class]]) {
        [picker dismissViewControllerAnimated:YES completion:nil];
        return;
    }
    MAPickerController *cameraPicker = (MAPickerController *)picker;
    if (cameraPicker.callBack) {
        cameraPicker.callBack(nil, [NSError errorWithDomain:@"QMASelectMedia" code:-1 userInfo:@{NSLocalizedDescriptionKey : QMA_API_Cancel}]);
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)selectMediaFromPickerWithModel:(QMAMediaChooseConfigModel *)model
                              parentVC:(UIViewController *)parentVC
                       completionBlock:(void (^)(NSArray *_Nullable, NSError *_Nullable))completionBlock {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:model.maxCount delegate:nil];
    imagePickerVc.allowPickingGif = NO;
    imagePickerVc.allowTakeVideo = NO;
    imagePickerVc.allowTakePicture = NO;
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        NSMutableArray *array = [NSMutableArray array];
        [photos enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            QMAPickerImageModel *imageModel = [[QMAPickerImageModel alloc] init];
            imageModel.image = obj;
            [array addObject:imageModel];
        }];
        if(completionBlock) {
            completionBlock(array, nil);
        }
    }];
    [parentVC presentViewController:imagePickerVc animated:YES completion:nil];
}

#pragma mark - 地理位置

- (void)requestLocation:(MALocationCompletionBlock)completionBlock {
    //TODO: 返回地理位置信息 宿主替换
    MALocationModel *model = [[MALocationModel alloc] init];
    model.location = [[CLLocation alloc] init];
    if(completionBlock) {
        completionBlock(YES, nil, model);
    }
}

- (UIImageView *)imageViewWithURL:(NSString *)url {
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectZero];
    if(url.length > 0) {
        [imageView sd_setImageWithURL:[NSURL URLWithString:url]];
    }
    return imageView;
}

- (NSInteger)maxMiniGameInstanceCount {
    return 2;
}

- (UIViewController *)createWebViewController:(QMAWebViewVCModel *)model {
    NSLog(@"open url %@",model.url);
    if(model.url.length == 0) {
        return nil;
    }
    SimpleWebViewController *vc = [[SimpleWebViewController alloc] initWithURL:[NSURL URLWithString:model.url]];
    vc.disableInteractivePopGestureRecognizer = YES;
    vc.forcePortrait = model.forcePortrait;
    return vc;
}


@end
